package com.ikangtai.shecare.personal.oad;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.services.ble.BLEThermometerService;
import com.ikangtai.shecare.common.util.AppLog;

public class OADMainActivity extends BaseActivity {

    private TopBar topBar;
    private String imageRevision;
    private String imageFileUrl;
    private boolean sign = false;
    private static BLEThermometerService mBLEThermometerService = null;
    private static boolean mScanning;
    private final long SCAN_PERIOD = 5000L;
    private BluetoothDevice mDevice = null;
    private static String action;
    private int scanSign = 0;
    private boolean mConnected = false;// 连接
    private int readnum_flag1 = 0;
    public final String DATABASE = "Database";
    private int THERMOMETER_CONNECTED_NUM = 0;
    private int THERMOMETER_CONNECTED_END_NUM = 0;
    private boolean isBLERegistered = false;

    private static final int GET_FIRMWARE_INFO_OK = 6;
    private static final int GET_FIRMWARE_INFO_NOK = 5;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_oad_main);
        Intent intent = getIntent();
        imageFileUrl = intent.getStringExtra("fileURL");
        initView();
        initBluetooth();
    }

    private void initView() {
        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        THERMOMETER_CONNECTED_NUM = 0;
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        //adapter不等于null，说明本机有蓝牙设备
        if (adapter != null) {
            AppLog.e("本机有蓝牙设备！");
            //如果蓝牙设备未开启
            if (adapter.isEnabled()) {
                if (mBLEThermometerService != null) {
                    operateThermometerScan(true);// 温度计扫描操作开始
                }
            }else{
            }
        }
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        isBLERegistered = true;
    }

    private void initBluetooth() {
        // 绑定服务
        Intent gattServiceIntent = new Intent(OADMainActivity.this, BLEThermometerService.class);
        sign = getApplicationContext().bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @SuppressLint("NewApi")
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            AppLog.e("OADMainActivity onServiceConnected");
            mBLEThermometerService = ((BLEThermometerService.LocalBinder) service).getService();
            // initialize初始化
            if (!mBLEThermometerService.initialize()) {// 如果温度计服务不初始化
                Toast.makeText(OADMainActivity.this, "手机蓝牙不可用", Toast.LENGTH_SHORT).show();
            } else {
                mBLEThermometerService.openBluetooth(OADMainActivity.this);
                if(BluetoothAdapter.getDefaultAdapter().isEnabled())
                    operateThermometerScan(true);// 温度计扫描操作打开
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBLEThermometerService = null;
        }
    };

    // 温度计扫描操作
    private void operateThermometerScan(final boolean enable) {
        AppLog.e("ThermometerService come in operateThermometerScan");
        if (mBLEThermometerService == null) {// 如果蓝牙温度计服务没有被绑定，就提示
            Toast.makeText(this, "蓝牙温度计未初始化！请稍等", Toast.LENGTH_SHORT).show();
            return;
        }

        if (enable) {
            AppLog.e("CalendarActivity begin operateThermometerScan");
            if (mBLEThermometerService.thermometers.size() == 0) {
                mScanning = mBLEThermometerService.scanThermometers(mLeScanCallback);
            }
        } else {
            mScanning = false;
            mBLEThermometerService.stopScanThermometers(mLeScanCallback); // 停止扫描温度计
        }
    }

    @SuppressLint("NewApi")
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            int i = 0;
            if (true) {
                AppLog.e("CalendarActivity LeScanCallback ThermometerSensor0");
                mBLEThermometerService.thermometers.add(device);
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ((mBLEThermometerService.autoConnect)
                            && (mBLEThermometerService.thermometers.size() > 0)) {
                        mBLEThermometerService.stopScanThermometers(mLeScanCallback);
                        mDevice = BluetoothAdapter.getDefaultAdapter()
                                .getRemoteDevice(device.getAddress());
                        AppLog.e("CalendarActivity LeScanCallback connectThermometer");
                        mBLEThermometerService.connectThermometer(mDevice
                                .getAddress());
                    }
                }
            });
        }
    };

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            action = intent.getAction();
            AppLog.e("onReceive action=" + action);
            if (BLEThermometerService.ThermometerMessage.THERMOMETER_FOUND.getName().equals(action)) {// 如果找到温度计的信息与程序定义的温度计信息一致
            }
            if (BLEThermometerService.ThermometerMessage.THERMOMETER_CONNECTED.getName().equals(action)) {// 连接成功
                updateConnectInfo();
            } else if (BLEThermometerService.ThermometerMessage.THERMOMETER_DISCONNECTED.getName()
                    .equals(action)) {// 断开连接温度计
                AppLog.e("THERMOMETER_DISCONNECTED");
                updateDisconnectInfo();
            } else if (BLEThermometerService.ThermometerMessage.FIRMWARE_TIMESYNC_FOUND.getName()
                    .equals(action)) {

            } else if (BLEThermometerService.ThermometerMessage.CLOSE_THERMOMETER_FOUND.getName()
                    .equals(action)) {

            } else if (BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_OPEN.getName()
                    .equals(action)) {
                AppLog.e("TEMPERATURE_MEASUREMENT_OPEN");
                mBLEThermometerService.writeOADImageRevision();
            } else if (BLEThermometerService.ThermometerMessage.BIND_PHONE_FOUND.getName()
                    .equals(action)) {
            } else if (BLEThermometerService.ThermometerMessage.FIRMWARE_REVISION_READ.getName().equals(action)) {
            } else if (BLEThermometerService.ThermometerMessage.OAD_IMAGE_REVISION_READ.getName().equals(action)) {
                 imageRevision = intent.getStringExtra(BLEThermometerService.ThermometerDataTag.OAD_IMAGE_REVISION_DATA.getName());
                AppLog.e("OAD_IMAGE_REVISION_DATA" + imageRevision);
            } else if (BLEThermometerService.ThermometerMessage.MEASUREMENT_INTERVAL_FOUND.getName()
                    .equals(action)) {
                AppLog.e("MEASUREMENT_INTERVAL_FOUND");
            } else if (BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_READ.getName()
                    .equals(action)) {

            } else if (BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_READ
                    .getName().equals(action)) {
                operateThermometerScan(true);
            }

        }

        private void updateDisconnectInfo() {
            mConnected = false;
            THERMOMETER_CONNECTED_NUM = 0;
            THERMOMETER_CONNECTED_END_NUM = 0;
            if (scanSign == 0) {
                scanSign = 1;
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public synchronized void run() {
                        scanSign = 0;
                        operateThermometerScan(true);// 温度计扫描操作打开
                    }
                }, SCAN_PERIOD);
                AppLog.e("THERMOMETER_DISCONNECTED postDelayed operateThermometerScan");
            }
        }

        private void updateConnectInfo() {
            mConnected = true;
            if (THERMOMETER_CONNECTED_NUM == 0) {
                THERMOMETER_CONNECTED_NUM = THERMOMETER_CONNECTED_NUM + 1;
            } else {
                THERMOMETER_CONNECTED_NUM = THERMOMETER_CONNECTED_NUM + 1;
            }
        }
    };
    private IntentFilter makeGattUpdateIntentFilter(){
        final IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_FOUND.getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_CONNECTED
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_DISCONNECTED
                .getName());
        intentFilter
                .addAction(BLEThermometerService.ThermometerMessage.RSSI_DATA_AVAILABLE.getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_OPEN
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_OPEN
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.HARDWARE_REVISION_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.BIND_PHONE_FOUND
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.FIRMWARE_TIMESYNC_FOUND
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.FIRMWARE_REVISION_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.CLOSE_THERMOMETER_FOUND
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.OAD_IMAGE_REVISION_READ
                .getName());

        return intentFilter;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        AppLog.e("-----onDestroy");
        operateThermometerScan(false);// 温度计扫描操作停止
        if(mGattUpdateReceiver!=null && isBLERegistered == true)
        {
            unregisterReceiver(mGattUpdateReceiver);// 不注册广播接收器
            isBLERegistered = false;
        }
        if(sign && mServiceConnection!=null)
        {
            getApplicationContext().unbindService(mServiceConnection);//解绑服务
            AppLog.e("onDestroy unbindService");
            sign=false;
        }
        getApplicationContext().stopService(new Intent(OADMainActivity.this, BLEThermometerService.class));
    }
}
